package cn.wintersun.baseweb.controller.user;


import cn.wintersun.basecommon.common.Result;
import cn.wintersun.basecommon.common.ResultCode;
import cn.wintersun.basecommon.context.BaseContext;
import cn.wintersun.baseweb.dao.FileDate;
import cn.wintersun.baseweb.service.intrer.ModelService;
import cn.wintersun.baseweb.service.intrer.user.FileDateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/model")
@RestController
@Slf4j
@PreAuthorize("hasAuthority('1')")
public class ModelController {

    @Value("${file.upload-folder}")
    private String UPLOAD_FOLDER;

    @Value("${file.save-folder}")
    private String SAVE_FOLDER;
    @Autowired
    private ModelService modelService;

    @Autowired
    private FileDateService fileDateService;

    /**
     * 运行模型
     * @param filePath
     * @return
     */
    @GetMapping("/run")
    public Result<Object> runModel(@RequestParam String filePath){
        log.info("运行模型:{}",filePath);
        // 检查文件是否存在
        Path path = Paths.get(UPLOAD_FOLDER + filePath);
        if (!Files.exists(path)) {
            log.error("文件不存在: {}", path);
            return Result.failure(ResultCode.UPLOAD_FILE_ERROR);
        }
        String currentId = BaseContext.getCurrentId().toString();
        int modelCode = modelService.runModel(filePath,currentId);
        if(modelCode == 0){
            FileDate fileDate = new FileDate();
            fileDate.setState(1);
            fileDate.setFilePath(filePath);
            fileDateService.updateFileDate(fileDate);
            return Result.ok(ResultCode.SUCCESS);
        }else{
            return Result.failure(ResultCode.MODEL_ERROR);
        }

    }

    @GetMapping("/get")
    public Result<List<byte[]>> getModelImages(String fileName){
        log.info("获取模型图片");
        Long userId = BaseContext.getCurrentId();
        List<byte[]> listByte = new ArrayList<>(); // 初始化 listByte
        for (int i = 1;i <= 27;i++){
            if(i == 8){
                continue;
            }
            try {
                Path path = Paths.get(SAVE_FOLDER + "picture/" +userId+"/"+fileName+"/"+ "figure" + i + ".png");
                //检查图片是否存在
                if (!Files.exists(path)) {
                    log.error("文件不存在: {}", path);
                    return Result.failure(500, "模型保存图片存在异常");
                }
                byte[] imageBytes = Files.readAllBytes(path);
                listByte.add(imageBytes);
            }catch (Exception e){
                log.info("出现错误:"+e);
                return Result.failure(ResultCode.SERVER_ERROR);
            }
        }
        return Result.ok(listByte);
    }

}
